<?php
class ElemeApiModel
{
    public $chnId;
    public $syncCnt; //批量同步数量

    public function __construct(){
        $this->chnId = 4;
        $this->syncCnt = 40;
    }
    
    /*
        查询店铺信息
        params
            store_id 门店ID
            chn_store_id 第三方门店ID
    */
    public function getShop($store_id = 0, $chn_store_id = 0)
    {
        $ElemeStoreSvc = new ElemeStoreSvc();

        $chn_store_id = intval($chn_store_id);
        $data = $ElemeStoreSvc->getShop($chn_store_id);

        $res = $ElemeStoreSvc->sendGetShop($data);

        if($res['error'] == null){
            $servingTime = $res['result']['servingTime'][0];
            $arr_servingTime = explode('-', $servingTime);
            $start_time = strtotime($arr_servingTime[0]) - strtotime("00:00:00");
            $end_time = strtotime($arr_servingTime[1]) - strtotime("00:00:00");

            $addStore = $this->addChannelStoreInfo(
                $this->chnId, $store_id, $chn_store_id,
                $res['result']['name'], $res['result']['description'],
                $start_time, $end_time,
                $res['result']['isOpen']
            );

            return $addStore;
        }else{
            $res = array(
                "errNo" => "2001",
                "data" => $res
            );
            return $res;
        }
    }

    /*
        添加第三方店铺信息
        params
            channel_id 第三方渠道id
            store_id 快方药店id
            shop_id 第三方店铺id
            shop_name 第三方店铺名称
            shop_desc 第三方店铺描述
            start_time 营业开始时间
            end_time 营业结束时间
            store_status 店铺状态
    */
    public function addChannelStoreInfo(
        $channel_id = 0, $store_id = 0, $shop_id = 0, 
        $shop_name = "", $shop_desc = "", 
        $start_time = 0, $end_time = 0,
        $store_status = 0
    ){
        $ChannelStoreModel = new ChannelStoreModel();

        $res = $ChannelStoreModel->addChannelStoreInfo(
            $channel_id, $store_id, $shop_id, 
            $shop_name, $shop_desc, 
            $start_time, $end_time,
            $store_status
        );

        return $res;
    }

    /*
        修改店铺信息
        params
            chn_id 渠道id
            store_id 店铺id
            other_shop_name 第三方药店名称
            other_shop_desc 第三方药店广告
            start_time 营业开始时间
            end_time 营业结束时间
            shipping_fee 配送费
            store_status 店铺状态
    */
    public function updateShop($chn_id = 0, $store_id = 0, $other_shop_name = '', $other_shop_desc = '', $start_time = '', $end_time = '', $shipping_fee = 0, $store_status = 0)
    {
        $storeInfo = $this->getStoreInfoById($store_id); //获取药店信息

        if(empty($storeInfo)){
            $res = array(
                "errNo" => "1001"
            );
            return $res;
        }

        $otherShopInfo = getChannelStoreInfo($this->chnId, $store_id);//获取第三方门店ID
        $other_shop_id = $otherShopInfo['other_shop_id'];

        $shipping_start_time  =  strtotime($start_time);
        $shipping_end_time  =  strtotime($end_time);

        $shipping_time = date('H:i',$shipping_start_time).'-'.date('H:i',$shipping_end_time);  // 门店营业时间 

        if($store_status == '0')
        {
            $isOpen = 0;  //门店的营业状态 ： 1营业 0不营业  
        }elseif ($store_status == 1) {
            $isOpen = 1; 
        }elseif ($store_status == 2) {
            $isOpen = 0; 
        }  

        $ElemeStoreSvc = new ElemeStoreSvc();

        $data = $ElemeStoreSvc->updateShop($other_shop_id, $other_shop_name, $other_shop_desc, $shipping_time, $shipping_fee, $isOpen);
        $res = $ElemeStoreSvc->sendUpdateShop($data);

        if($res['error'] == null){
            $location_start_time = strtotime($start_time) - strtotime('00:00:00');
            $location_end_time = strtotime($end_time) - strtotime('00:00:00');

            $updateStore = updateChannelStoreInfo($chn_id, $store_id, $other_shop_name, $other_shop_desc, $location_start_time, $location_end_time, $shipping_fee, $store_status);
            return $updateStore;
        }else{
            $res = array(
                "errNo" => "2001",
                "data" => $res
            );
            return $res;
        }
    }


    /*
        初始化自定义分类
        params
            store_id 店铺id
    */
    public function initCategoryInfo($store_id = '')
    {
        $defaultCategory = $GLOBALS['defaultCategory'];

        foreach ($defaultCategory as $key => $value) {
            $this->createCategory($store_id, $key, $value, 1);
        }

        return true;
    }

    /*
        添加商品分类
        params
            shopId    int  是     店铺ID   
            category_id     string  是   商品分类ID  
            category_name     string  是   商品分类名称  
            description   string  否   药品分类描述
    */
    public function createCategory($shopId = '', $category_id = '', $category_name = '', $description = '')
    {
        $ElemeCategorySvc = new ElemeCategorySvc();

        $otherShopInfo = getChannelStoreInfo($this->chnId, $shopId);
        $other_shop_id = $otherShopInfo['other_shop_id'];

        $data = $ElemeCategorySvc->createCategory($other_shop_id, $category_name, $description);
        $res = $ElemeCategorySvc->sendCreateCategory($data);
        
        if($res['error'] == null){
            $other_category_id = $res['result']['id'];
            $other_category_name = $res['result']['name'];
            $addCategory = addChannelCategoryInfo($this->chnId, $shopId, $category_id, $other_category_id, $other_category_name, $sequence);

            return $addCategory;
        }else{
            $res = array(
                "errNo" => "2002",
                "data" => $res
            );
            return $res;
        }
    }

    /*
        修改商品分类
        params
            other_category_id    string  是   第三方商品分类ID   
            other_category_name  string  是   第三方商品分类名称
    */
    public function updateCategory($other_category_id = '', $other_category_name = '')
    {
        $ElemeCategorySvc = new ElemeCategorySvc();

        $data = $ElemeCategorySvc->updateCategory($other_category_id, $other_category_name);
        $res = $ElemeCategorySvc->sendUpdateCategory($data);

        if($res['error'] == null){
            $save = updateChannelCategoryInfo($other_category_id, $other_category_name);

            return $save;
        }else{
            $res = array(
                "errNo" => "2003",
                "data" => $res
            );
            return $res;
        }
    }

    /*
        删除商品分类
        params
            store_id  int  是  店铺ID
            other_category_id    string  是   商品分类ID   
    */
    public function removeCategory($store_id = 0, $other_category_id = 0)
    {
        $ElemeCategorySvc = new ElemeCategorySvc();

        $data = $ElemeCategorySvc->removeCategory($other_category_id);
        $res = $ElemeCategorySvc->sendRemoveCategory($data);

        if($res['error'] == null){
            $del = delChannelCategoryInfo($this->chnId, $store_id, $other_category_id);

            return $del;
        }else{
            $res = array(
                "errNo" => "2005",
                "data" => $res
            );
            return $res;
        }
    }

    /*
        添加商品
        params
            store_id 店铺id
            product_id 快方商品id
            other_category_id 第三方分类id
    */
    public function createItem($store_id = 0, $product_id = 0, $other_category_id = 0)
    {
        $productInfo = getProductInfoById($product_id);

        if(empty($productInfo)){
            $res = array(
                "errNo" => "3001"
            );

            return $res;
        }

        $product_name = $productInfo['Caption'];
        $description = $productInfo['ShortMemo'];
        $barCode = $productInfo['BarCode'];
        $sale_price = $productInfo['LSJG'];
        $onShelf = 1;
        $thumb = array($productInfo['Pic1']);
        $specName = $productInfo['ModeSize'];

        $ElemeProductSvc = new ElemeProductSvc();

        $image = $ElemeProductSvc->uploadImageWithRemoteUrl($productInfo['Pic1']);
        $imageHash = $ElemeProductSvc->sendUploadImageWithRemoteUrl($image);

        $specsInfo = $ElemeProductSvc->getItemSpecs($specId, $specName, $sale_price, $stock, $maxStock, $packingFee, $onShelf, $extendCode, $barCode, $weight, $activityLevel);

        $data = $ElemeProductSvc->createItem($other_category_id, $product_name, $description, $imageHash, $specsInfo);
        
        $res = $ElemeProductSvc->sendCreateItem($data);

        if($res['error'] == null){
            $other_product_id = $res['result']['id'];
            $other_spec_id = $res['result']['specs'][0]['specId'];

            $add = addChannelProductInfo($this->chnId, $store_id, $product_id, $other_category_id, $other_product_id, $sale_price*100, $thumb, $other_spec_id);

            return $add;
        }else{
            $res = array(
                "errNo" => "2010",
                "data" => $res
            );
            return $res;
        }
        
    }

    /*
        修改商品
        params
            other_product_id 第三方商品id
            other_category_id 第三方分类id
            other_product_name 第三方商品名称
    */
    public function updateItem($other_product_id = 0, $other_category_id = 0, $other_product_name = '')
    {
        // $productInfo = getProductInfoById($product_id);

        // if(empty($productInfo)){
        //     $res = array(
        //         "errNo" => "3001"
        //     );

        //     return $res;
        // }

        // $product_name = $productInfo['Caption'];
        // $description = $productInfo['ShortMemo'];
        // $barCode = $productInfo['BarCode'];
        // $sale_price = $productInfo['LSJG'];
        // $onShelf = 1;
        // $thumb = array($productInfo['Pic1']);

        // $specId = 1286240589;
        // $specName = '规格名称';
        // $sale_price = 10;
        // $stock = 0;
        // $maxStock = 100;
        // $packingFee = 1.0;
        // $onShelf = 1;
        // $extendCode = '1234567890290';
        // $barCode = 'x123456';
        // $weight = 12;
        // $activityLevel = 1;

        // $ElemeProductSvc = new ElemeProductSvc();

        // // $image = $ElemeProductSvc->uploadImageWithRemoteUrl($productInfo['Pic1']);
        // // $imageHash = $ElemeProductSvc->sendUploadImageWithRemoteUrl($image);

        // $specsInfo = $ElemeProductSvc->getItemSpecs($specId, $specName, $sale_price, $stock, $maxStock, $packingFee, $onShelf, $extendCode, $barCode, $weight, $activityLevel);

        // $data = $ElemeProductSvc->updateItem($other_product_id, $other_category_id, $other_product_name, $imageHash, $specsInfo);
        
        // $res = $ElemeProductSvc->sendUpdateItem($data);
        // var_dump($res);die;

        // if($res['error'] == null){
        //     $other_product_id = $res['result']['id'];
        //     $add = updateChannelProductInfo($this->chnId, $store_id, $product_id, $other_category_id, $other_product_id, $sale_price*100, $thumb);

        //     return $add;
        // }else{
        //     $res = array(
        //         "errNo" => "2010",
        //         "data" => $res
        //     );
        //     return $res;
        // }
        
    }

    /*
        删除商品
        params
            store_id   店铺ID
            other_product_id 第三方商品id
    */
    public function deleteItem($store_id = 0, $other_product_id = 0)
    {
        $data = $ElemeProductSvc->removeItem($other_product_id);
        
        $res = $ElemeProductSvc->sendRemoveItem($data);
        var_dump($res);die;

        if($res['error'] == null){
            $other_product_id = $res['result']['id'];
            $add = updateChannelProductInfo($this->chnId, $store_id, $product_id, $other_category_id, $other_product_id, $sale_price*100, $thumb);

            return $add;
        }else{
            $res = array(
                "errNo" => "2010",
                "data" => $res
            );
            return $res;
        }
        
    }

    /*
        获取药店信息
        params
            store_id 药店id
    */
    public function getStoreInfoById($store_id = 0)
    {
        $StoreModel = new StoreModel();

        return $StoreModel->getStoreInfoById($store_id);
    }

    /*
        同步商品库存信息
        params
            data 商品库存信息
    */
    public function syncStock($data = array())
    {
        $productData = array();

        foreach ($data as $key => $value) {
            $productInfo = getChannelProductSpecID($this->chnId, $value['store_id'], $value['other_product_id']);

            $productData[$key]['itemId'] = $value['other_product_id'];
            $productData[$key]['specId'] = $productInfo['other_spec_id'];
            $productData[$key]['stock'] = $value['product_stock'];
            $productData[$key]['store_id'] = $value['store_id'];
        }

        $ElemeProductSvc = new ElemeProductSvc();
        
        $Dao = M("kfsy_channel_store.kf_channel_product");
        $Dao->startTrans();

        foreach ($productData as $k => $v) {
            $updateStock = updateChannelProductStock($this->chnId, $v['store_id'], $v['itemId'], array('product_stock' => $v['stock']));

            if($updateStock == false){
                $Dao->rollback();
                unset($productData[$k]);
                continue;
            }
        }

        $sendData = array();
        foreach ($productData as $key => $value) {
            $sendData[] = $ElemeProductSvc->batchUpdateSpecStocks($value['itemId'], $value['specId'], $value['stock']);
        }

        $result = $this->updateStockBatch($sendData);

        if($result['error'] == null){
           $Dao->commit();
        }else
        {
            $Dao->rollback();
            return false;
        }

        return true;
    }

    /*
        批量同步库存信息
        params
            stock 库存信息对象
    */
    public function updateStockBatch($sendData = array())
    {
        $ElemeProductSvc = new ElemeProductSvc();

        $data = $ElemeProductSvc->batchUpdateSpecStocksData($sendData);

        $res = $ElemeProductSvc->sendBatchUpdateSpecStocks($data);

        return $res;
    }

    /*
        同步商品价格信息
        params
            other_shop_id 店铺id
            data 商品价格信息
    */
    public function syncPrice($data = array())
    {
        // $data = array(
        //     array(
        //          'store_id' => 3,   
        //          'other_product_id' => 1287474098,
        //          'product_price' => 1800   
        //     ),
        //     array(
        //          'store_id' => 3,   
        //          'other_product_id' => 1288083900,
        //          'product_price' => 1800   
        //     ),
        // );

        $productData = array();

        foreach ($data as $key => $value) {
            $productInfo = getChannelProductSpecID($this->chnId, $value['store_id'], $value['other_product_id']);

            $productData[$key]['itemId'] = $value['other_product_id'];
            $productData[$key]['specId'] = $productInfo['other_spec_id'];
            $productData[$key]['price'] = $value['product_price'];
            $productData[$key]['store_id'] = $value['store_id'];
        }

        $other_shop_id = array();
        $new_data = array();

        foreach ($productData as $key => $value) {
            $other_shop_id = getOtherShopIdByRedis($this->chnId, $value['store_id']);

            $new_data[$other_shop_id][] = $value;

        }

        $ElemeProductSvc = new ElemeProductSvc();
        $Dao = M("kfsy_channel_store.kf_channel_product");
        $Dao->startTrans();
        
        foreach ($new_data as $key => $value) {

            foreach ($value as $k => $v) {
                $updatePrice = updateChannelProductPrice($this->chnId, $v['store_id'], $v['itemId'], array('product_price' => $v['price']));

                if($updatePrice == false){
                    $Dao->rollback();
                    unset($value[$k]);
                    continue;
                }
            }
            
            $sendData = array();
            foreach ($value as $k1 => $v1) {
                $sendData[] = $ElemeProductSvc->batchUpdatePrices($v1['itemId'], $v1['specId'], $v1['price']/100);
            }

            $res = $this->updatePriceBatch($key, $sendData);

            if($res['error'] == null){
                $Dao->commit();
                // var_dump($res);
                // var_dump('success');
                // die;
            }else
            {
                $Dao->rollback();
                // var_dump($res);
                // var_dump('error');
                // die;
                return false;
            }

        }

    }

    /*
        批量同步价格信息
        params
            other_shop_id 店铺id
            sendData 价格信息对象
    */
    public function updatePriceBatch($other_shop_id = 0, $sendData = array())
    {
        $ElemeProductSvc = new ElemeProductSvc();

        $data = $ElemeProductSvc->batchUpdateSpecStocksData($sendData);

        $res = $ElemeProductSvc->sendBatchUpdateSpecStocks($data);

        return $res;
    }
  
}

